package com.sun.mongodb.core.listenner;

import com.sun.mongodb.core.util.SpringContextHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;

/**
 * Created by Administrator on 2021/9/6.
 */
public class SpringContextHolderListenner implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ApplicationContext context = event.getApplicationContext();

        BeanDefinitionBuilder beanFactory = BeanDefinitionBuilder.rootBeanDefinition(SpringContextHolder.class);
//        beanFactory.setInitMethodName("init");
        beanFactory.setScope("prototype");  //  多例

        beanFactory.addConstructorArgValue(context);
        DefaultListableBeanFactory autowireCapableBeanFactory =(DefaultListableBeanFactory)context.getAutowireCapableBeanFactory();  // 帮我们做自动注入
        String registerBeanNm ="defaultSpringContextHolder";
        autowireCapableBeanFactory.registerBeanDefinition(registerBeanNm,beanFactory.getBeanDefinition());

        SpringContextHolder contextHolder = (SpringContextHolder)context.getBean(registerBeanNm);
//        contextHolder.setApplicationContext(context);
    }
}
